<?php

namespace hpnApp\nCtrl {

require_once(ABSPATH . '/MiiLib/Cmn.php');

use \hpnWse\stNumUtil;
use \hpnWse\stStrUtil;
use \hpnWse\stObjUtil;
use \hpnWse\stAryUtil;
use \hpnWse\stHttpSvc;
use \hpnWse\stSqlUtil;
use \hpnWse\tPgntCch;
use \hpnWse\nWp\stBase as stWpBase;

/// 控制器 - 问题
class stCtrl_question extends \hpnWse\stCtrl
{
	public static function POST_upload_image($a_Help, &$a_Prms)
	{
		if ($a_Help)
		{
			return parent::sdHelp('上传文章图像');
		}

		if (\hpnWse\fBool($l_VldtRst = \hpnApp\fVldtUser(3)))
		{ return $l_VldtRst; }
		
		$l_Uid = $_SESSION['UserProfile']['Id'];

		if (isset($_FILES['file_binary']))
		{
			$l_SrcData = $_FILES['file_binary'];
		}
		else
		if (isset($_POST['file_base64']))
		{
			$l_SrcData = $_POST['file_base64'];
		}
		else
		{
			return stHttpSvc::cRspsErr(400, -2, '上传文件过大！');
		}

		require_once(\hpnWse\fGetWseDiry() . 'hpnWse/nSpu/FileUpld.php');

		$l_Rst = \hpnWse\nSpu\stFileUpld::cRun(array(
			'c_DstDiry' => ABSPATH . '/uploads_question/',
			'c_SrcData' => $l_SrcData
		));

		$l_Url = site_url() . '/uploads_question/' . $l_Rst['c_Flnm'];
		$l_Rst = array(
			'data' => $l_Url
		);
		return $l_Rst;
	}

	public static function POST_new($a_Help, &$a_Prms)
	{
		if ($a_Help)
		{
			return parent::sdHelp('新问题');
		}

		if (\hpnWse\fBool($l_VldtRst = \hpnApp\fVldtUser(5)))
		{ return $l_VldtRst; }

		////////////////////////////////【测试】
		$l_Rst = array(
			'data' => array(
				'url' => 'http://192.168.1.187/wordpress/52.html',
				'categories' => ['其他问题']
			)
		);
		return $l_Rst;
		////////////////////////////////

		$l_Uid = $_SESSION['UserProfile']['Id'];

		// 检查并过滤提交数据
		$l_Tit = strip_tags(trim($a_Prms['json']['title']));
		$l_Desc = strip_tags(trim($a_Prms['json']['desc']));
		$l_Imgs = $a_Prms['json']['imgs'];
		for ($i=0; $i<3; ++$i)
		{ $l_Imgs[$i] = strip_tags(stObjUtil::cFchPpty($l_Imgs, $i, '')); }

		$l_Len = stStrUtil::cGetLen($l_Tit);
		if ($l_Len < 2)
		{
			return stHttpSvc::cRspsErr(400, -2, '标题至少 2 个字！');
		}

		if ($l_Len > 30) { $l_Tit = stStrUtil::cSub($l_Tit, 0, 30); }

		$l_Len = stStrUtil::cGetLen($l_Desc);
		if ($l_Len > 500) { $l_Desc = stStrUtil::cSub($l_Desc, 0, 500); }

		// 根据标题和描述判断分类
		require_once(ABSPATH . '/lib/CategoryDictionary.php');

		$l_CtgrSlugs = array();
		foreach ($g_CtgrDic as $l_Key => $l_Slugs)
		{
			if (stStrUtil::cFind($l_Tit, $l_Key) >= 0)
			{
				$l_CtgrSlugs = explode(',', $l_Slugs);
				break;
			}
		}

		if (0 == count($l_CtgrSlugs))
		{
			$l_CtgrSlugs = array('others');
		}

		$l_CtgrIds = $l_CtgrSlugs;
		$l_CtgrNames = array();

		array_unshift($l_CtgrIds, 'subjects');
		foreach ($l_CtgrIds as $l_Idx => $l_Slug)
		{
			$l_WpCtgr = get_category_by_slug($l_Slug);
			$l_CtgrIds[$l_Idx] = $l_WpCtgr->term_id;
			if ($l_Idx > 0)
			{
				$l_CtgrNames[] = $l_WpCtgr->name;
			}
		}

		$l_ArtcData = array(
			'post_author' => $l_Uid,
			'post_title' => $l_Tit,
			'post_content' => $l_Desc,
			'post_status' => 'publish',
			'post_category' => $l_CtgrIds
		);
		$l_Qid = wp_insert_post($l_ArtcData);

		if (! $l_Qid)
		{
			return stHttpSvc::cRspsErr(500, -1, '录入数据库时发生未知错误！');
		}

		// 如果有图像，添加元数据，否则等到需要时
		if ($l_Imgs[0] || $l_Imgs[1] || $l_Imgs[2])
		{
			$l_Pdo = stHttpSvc::cCnctToDb();
			$l_Rst = self::eIstQstnMeta($l_Pdo, $l_Qid, $l_Imgs, 0, 0, 0);
			if ($l_Rst)
			{ return $l_Rst; }
		}


		// 返回提示信息
		$l_Url = site_url() . '/' . $l_Qid . '.html';
		$l_CtgrNames = implode('，', $l_CtgrNames);

		$l_Rst = array(
			'data' => array(
				'url' => $l_Url,
				'categories' => $l_CtgrNames
			)
		);
		return $l_Rst;
	}

	public static function POST_appraise($a_Help, &$a_Prms)
	{
		if ($a_Help)
		{
			return parent::sdHelp('更改评价，若已赞/踩过则撤销，否则赞/踩',
				array(
					'c_Qid' => '问题ID',
					'c_Which' => '哪一项？{ "Pstv", "Ngtv" }'
				));
		}

		if (\hpnWse\fBool($l_VldtRst = \hpnApp\fVldtUser(0)))
		{ return $l_VldtRst; }

		$l_Uid = $_SESSION['UserProfile']['Id'];

		$l_Json = &$a_Prms['json'];
		$l_Qid = intval(stObjUtil::cFchPpty($l_Json, 'c_Qid', 0)); // 转成整数，查询时可以放心
		$l_Which = stObjUtil::cFchPpty($l_Json, 'c_Which');
		$l_IsPstv = ('Pstv' == $l_Which);
		$l_IsNgtv = ('Ngtv' == $l_Which);
		if (!$l_IsPstv && !$l_IsNgtv)
		{
			return stHttpSvc::cRspsErr(400, -2, 'c_Which参数错误！');
		}

		$l_Val = $l_IsPstv ? +1 : -1;

		// 查询
		$l_Db = DB_NAME;

$l_Sql = <<<SQL
SELECT mAppraise AS Aprs
FROM $l_Db.tt_user__question__appraise AS tA
WHERE (tA.mUserId = $l_Uid) AND (tA.mQuestionId = $l_Qid)
SQL;

// 数据库里有外键约束
//INNER JOIN $l_Db.t_user AS tU
//ON (tA.mUserId = tU.mId)
//INNER JOIN $l_Db.wp_posts AS tP
//ON (tA.mQuestionId = tP.ID)

		$l_Pdo = stHttpSvc::cCnctToDb();
		$l_Aprs = stSqlUtil::cPrprExecFchNum($l_Pdo, $l_Sql);
		
		if (null === $l_Aprs)
		{
$l_Sql = <<<SQL
INSERT INTO $l_Db.tt_user__question__appraise
(mUserId, mQuestionId, mAppraise)
VALUES
($l_Uid, $l_Qid, $l_Val)
SQL;
			$l_Aprs = 0; // 插入后，同0
		}
		else
		{
			if (0 !== $l_Aprs)
			{
				$l_Val = 0;
			}

$l_Sql = <<<SQL
UPDATE $l_Db.tt_user__question__appraise AS tA
SET mAppraise = $l_Val
WHERE (tA.mUserId = $l_Uid) AND (tA.mQuestionId = $l_Qid)
SQL;
		}

		$l_Afcd = stSqlUtil::cPrprExec($l_Pdo, $l_Sql);
		if (1 !== $l_Afcd)
		{
			$l_Rst = array(
				'data' => 0
			);
			return $l_Rst;	
		}

		// 接下来还要更新问题元数据表
		$l_Add = (0 == $l_Aprs) ? +1 : -1;
		$l_Col = $l_IsPstv ? 'mPositive' : 'mNegative';
		$l_Afcd = self::eChgQstnMetaCnt($l_Pdo, $l_Qid, $l_Col, $l_Add);
		

		$l_Rst = array(
			'data' => $l_Afcd
		);
		return $l_Rst;
	}

	// 插入问题元数据
	private static function eIstQstnMeta($a_Pdo, $a_Qid, $a_Imgs, $a_Pstv, $a_Ngtv, $a_Fav)
	{
		$l_Imgs = array();
		for ($i=0; $i<3; ++$i)
		{
			if ($a_Imgs[$i]) { $l_Imgs[] = $a_Imgs[$i]; }
		}
		while (count($l_Imgs) < 3)
		{
			$l_Imgs[] = '';
		}
		$l_Imgs = implode(';', $l_Imgs);


		// 查询
		$l_Db = DB_NAME;

$l_Sql = <<<SQL
INSERT INTO $l_Db.t_question_meta
(mQuestionId, mImages, mPositive, mNegative, mFavorite)
VALUES
($a_Qid, :mImgs, $a_Pstv, $a_Ngtv, $a_Fav)
SQL;
		try
		{
			$l_Afcd = stSqlUtil::cPrprExec($a_Pdo, $l_Sql,
				array(
					'mImgs' => $l_Imgs
				));
		}
		catch (\Exception $a_Exc)
		{
			stHttpSvc::cLog($a_Exc->getMessage());
		}
		if (1 !== $l_Afcd)
		{
			return stHttpSvc::cRspsErr(500, -2, '录入数据库时发生未知错误！');
		}
		return null;
	}

	// 改变计数
	private static function eChgQstnMetaCnt($a_Pdo, $a_Qid, $a_Col, $a_Add)
	{
		// 查询有没有元记录
		$l_Db = DB_NAME;

/*
$l_Sql = <<<SQL
SELECT COUNT(*)
FROM $l_Db.t_question_meta
WHERE (mQuestionId = $a_Qid)
SQL;
	
		$l_Amt = stSqlUtil::cPrprExecFchNum($a_Pdo, $l_Sql);

		if (0 == $l_Amt)
		{
			$l_Pstv = ('mPositive' == $a_Col) ? 1 : 0;
			$l_Ngtv = ('mNegative' == $a_Col) ? 1 : 0;
			$l_Fav = ('mFavorite' == $a_Col) ? 1 : 0;

$l_Sql = <<<SQL
INSERT INTO $l_Db.t_question_meta
(mQuestionId, mImages, mPositive, mNegative, mFavorite)
VALUES
($a_Qid, ';;', $l_Pstv, $l_Ngtv, $l_Fav)
SQL;
		}
		else
		{
$l_Sql = <<<SQL
UPDATE $l_Db.t_question_meta
SET $a_Col = $a_Col + 1
WHERE (mQuestionId = $a_Qid)
SQL;
		}
*/

		$l_Pstv = (('mPositive' == $a_Col) && ($a_Add > 0)) ? 1 : 0;
		$l_Ngtv = (('mNegative' == $a_Col) && ($a_Add > 0)) ? 1 : 0;
		$l_Fav  = (('mFavorite' == $a_Col) && ($a_Add > 0)) ? 1 : 0;

$l_Sql = <<<SQL
INSERT INTO $l_Db.t_question_meta
(mQuestionId, mImages, mPositive, mNegative, mFavorite)
VALUES
($a_Qid, ';;', $l_Pstv, $l_Ngtv, $l_Fav)
ON DUPLICATE KEY UPDATE
$a_Col = $a_Col + $a_Add
SQL;

		$l_Afcd = stSqlUtil::cPrprExec($a_Pdo, $l_Sql);
		return $l_Afcd; // “ON DUPLICATE KEY UPDATE”可能是2
	}


	public static function POST_favorite($a_Help, &$a_Prms)
	{
		if ($a_Help)
		{
			return parent::sdHelp('更改收藏',
				array(
					'c_Qid' => '问题ID'
				));
		}

		if (\hpnWse\fBool($l_VldtRst = \hpnApp\fVldtUser(0)))
		{ return $l_VldtRst; }

		$l_Uid = $_SESSION['UserProfile']['Id'];

		$l_Json = &$a_Prms['json'];
		$l_Qid = intval(stObjUtil::cFchPpty($l_Json, 'c_Qid', 0)); // 转成整数，查询时可以放心

		// 查询
		$l_Db = DB_NAME;

$l_Sql = <<<SQL
SELECT COUNT(*)
FROM $l_Db.tt_user__question__favorite AS tF
WHERE (tF.mUserId = $l_Uid) AND (tF.mQuestionId = $l_Qid)
SQL;

		$l_Pdo = stHttpSvc::cCnctToDb();
		$l_Like = stSqlUtil::cPrprExecFchNum($l_Pdo, $l_Sql);
		
		if ((null === $l_Like) || (0 === $l_Like))
		{
$l_Sql = <<<SQL
INSERT INTO $l_Db.tt_user__question__favorite
(mUserId, mQuestionId)
VALUES
($l_Uid, $l_Qid)
SQL;
			$l_Like = 0; // 插入后，同0
		}
		else
		{
			//【这里不能用别名！！！】
$l_Sql = <<<SQL
DELETE FROM $l_Db.tt_user__question__favorite
WHERE (mUserId = $l_Uid) AND (mQuestionId = $l_Qid)
LIMIT 1
SQL;
		//	stHttpSvc::$c_Dbg['dsql'] = $l_Sql;
		}

		$l_Afcd = stSqlUtil::cPrprExec($l_Pdo, $l_Sql);
		if (1 !== $l_Afcd)
		{
			$l_Rst = array(
				'data' => 0
			);
			return $l_Rst;	
		}

		// 接下来还要更新问题元数据表
		$l_Add = (0 == $l_Like) ? +1 : -1;
		$l_Afcd = self::eChgQstnMetaCnt($l_Pdo, $l_Qid, 'mFavorite', $l_Add);

		$l_Rst = array(
			'data' => $l_Afcd
		);
		return $l_Rst;
	}


	public static function GET_of_category($a_Help, &$a_Prms)
	{
		global $wpdb, $post;

		if ($a_Help)
		{
			return parent::sdHelp('获取指定分类的多篇文章', 
				array('json' => 'stWpBase::cGetArtcsOfCtgr的参数'), 
				array('data' => 'WP文章'));
		}

		$l_QryPrms = $a_Prms['json'];
		$l_Slug = stObjUtil::cFchPpty($l_QryPrms, 'c_Slug', 'others'); // slug
		if ('latest' == $l_Slug) // 全部分类的最新问题
		{ $l_Slug = 'subjects'; }
		$l_QryPrms['c_Slug'] = $l_Slug;
		
		$l_Ctgr = get_category_by_slug($l_Slug);
		// $l_SortBy = $l_QryPrms['c_SortBy'];
		// $l_SortByLen = strlen($l_SortBy);
		// $l_SortKey = stStrUtil::cSub($l_SortBy, 0, $l_SortByLen - 1);
		// $l_SortDir = stStrUtil::cSub($l_SortBy, $l_SortByLen - 1);
		// $l_SortDir = ('-' === $l_SortDir) ? 'DESC' : 'ASC';
		$l_MdlBgn = stObjUtil::cFchPpty($l_QryPrms, 'c_Ofst', 0);
		$l_MdlAmt = stObjUtil::cFchPpty($l_QryPrms, 'c_Cpct', 10);

		// 以下信息由本程序定制，不使用WP內建
		$l_QryPrms['c_NeedAuthor'] = $l_QryPrms['c_NeedFigure'] = false;


		// 查询
		$l_Db = DB_NAME;

$l_Sql = <<<SQL
SELECT tP.ID, tP.post_title, tP.post_date, tP.post_content, tP.comment_count,
	tU.mUsername AS Athr, 
	tU.mAvatar AS Ava,
	IFNULL(tQM.mImages, '') AS Imgs,
	IFNULL(tQM.mPositive, 0) AS Pstv, 
	IFNULL(tQM.mNegative, 0) AS Ngtv, 
	IFNULL(tQM.mFavorite, 0) AS Fav
FROM $l_Db.wp_posts AS tP

INNER JOIN $l_Db.wp_term_relationships AS tTR
on tP.ID = tTR.object_id
INNER JOIN $l_Db.wp_term_taxonomy AS tTT
ON tTR.term_taxonomy_id = tTT.term_taxonomy_id
INNER JOIN $l_Db.wp_terms AS tT
ON tTT.term_id = tT.term_id

INNER JOIN $l_Db.t_user AS tU
ON tP.post_author = tU.mId
LEFT JOIN $l_Db.t_question_meta AS tQM
ON tP.ID = tQM.mQuestionId

WHERE (tP.post_type = 'post') AND (tP.post_status = 'publish') AND (tT.slug = '$l_Slug')
ORDER BY tP.post_date DESC
SQL;
		
		$l_PC = new \hpnWse\tPgntCch(array(
			'c_Sql' => $l_Sql,
			'c_StoDiry' => ABSPATH . '/QstnCch/',
			'c_Trk' => $l_Slug,
			'c_PageCpct' => 100,
			'c_MaxTot' => 1e4,
			'c_RfshItvl' => 24 * 60 * 60
		));


	//	$l_PageData = $l_PC->cFchRcds($l_MdlBgn, $l_MdlAmt); // 10,19

		$l_PageData = stSqlUtil::cPrprExecFchAll(stHttpSvc::cCnctToDb(), $l_Sql);

		\hpnApp\fSuplDftsForQstns($l_PageData); // 补充默认值


		// 查询文章
		//$l_PageData = stWpBase::cGetArtcsOfCtgr($l_QryPrms);
		
		// $l_Qry = new \WP_Query(array(
		// 	'category_name'=> $l_Slug, 
		// 	'post_type' => 'post',
		// 	'posts_per_page'=> stObjUtil::cFchPpty($l_QryPrms, 'c_Cpct', 10), 
		// 	'offset'=> stObjUtil::cFchPpty($l_QryPrms, 'c_Ofst', 0))
		// );
		// $l_PageData = stWpBase::cQryArtcs($l_Qry, $l_QryPrms);
		
		// // 补充定制数据
		// if (stObjUtil::cFchPpty($l_QryPrms, 'c_AppNeedAthr'))
		// {
		// 	\hpnApp\fFchAthrForQstns($l_PageData);
		// }

		// if (stObjUtil::cFchPpty($l_QryPrms, 'c_AppNeedMeta'))
		// {
		// 	\hpnApp\fFchMetaForQstns($l_PageData);
		// }

		$l_Rst = array(
			'data' => $l_PageData
		);
		return $l_Rst;
	}

	// public static function GET_hot_articles_of_category($a_Help, &$a_Prms)
	// {
	// 	if ($a_Help)
	// 	{
	// 		return parent::sdHelp('获取指定分类的多篇热门文章', 
	// 			array('json' => 'stWpBase::cGetArtcsOfCtgr的参数'), 
	// 			array('data' => 'WP文章'));
	// 	}

	// 	$l_QryPrms = $a_Prms['json'];
	// //	$l_Slug = stObjUtil::cFchPpty($l_QryPrms, 'c_Slug', 'zysc'); // slug
	// //	$l_Ctgr = get_category_by_slug($l_Slug);
	// //	$l_Tot = $l_Ctgr ? $l_Ctgr->category_count : 0;
	// 	$l_PageData = stWpBase::cGetMostReadCntArtcs($l_QryPrms);

	// 	$l_Rst = array(
	// 		'data' => $l_PageData
	// 	);
	// 	return $l_Rst;
	// }

	public static function GET_rand_articles_of_category($a_Help, &$a_Prms)
	{
		if ($a_Help)
		{
			return parent::sdHelp('获取指定分类的多篇热门文章', 
				array('json' => 'stWpBase::cGetArtcsOfCtgr的参数'), 
				array('data' => 'WP文章'));
		}

		$l_QryPrms = $a_Prms['json'];
	//	$l_Slug = stObjUtil::cFchPpty($l_QryPrms, 'c_Slug', 'zysc'); // slug
	//	$l_Ctgr = get_category_by_slug($l_Slug);
	//	$l_Tot = $l_Ctgr ? $l_Ctgr->category_count : 0;
		$l_PageData = stWpBase::cRandArtcsOfCtgr($l_QryPrms);

		$l_Rst = array(
			'data' => $l_PageData
		);
		return $l_Rst;
	}
}

} // namespace \hpnApp\nCtrl

//////////////////////////////////// OVER ////////////////////////////////////